package com.zr.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.zr.dao.TreeDataDao;
import com.zr.util.GetJDBCUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class TreeDataDaoImpl implements TreeDataDao{

	GetJDBCUtil gt = new GetJDBCUtil();
	
	@Override
	public JSONArray getTreeDataOneById(int tpid) {
		Connection con = gt.getJDBCConnection();
		JSONArray jArray = new JSONArray();
		
		StringBuffer sql = new StringBuffer(""); 
		sql.append("SELECT * ");
		sql.append("FROM e_type ");
		sql.append("WHERE tpid=?");
		
		try {
			PreparedStatement pst = con.prepareStatement(sql.toString());
			pst.setInt(1, tpid);
			ResultSet rs = pst.executeQuery();
			
			while(rs.next()){
				JSONObject jObject = new JSONObject();
				jObject.put("id", rs.getInt("tid"));
				jObject.put("text", rs.getString("tname"));
				jObject.put("state", rs.getString("tstate"));
				jArray.add(jObject);
			}
			
			rs.close();
			pst.close();
			con.close();
		
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jArray;
	}

	@Override
	public JSONArray getTreeDataAllById(int tpid) {
		JSONArray userData = this.getTreeDataOneById(tpid);
		for (int i = 0; i < userData.size(); i++) {
			
			String state = userData.getJSONObject(i).getString("state");
			if ("open".equals(state)) {
				continue;
			}else{
				int currentId  = userData.getJSONObject(i).getInt("id");
				JSONArray children = this.getTreeDataAllById(currentId);
				userData.getJSONObject(i).put("children", children);
			}
		}
		
		return userData;
	}

}
